package com.skp.shaphan.ui.results;

import java.awt.FontMetrics;
import java.sql.ResultSet;

import javax.swing.JTable;
import javax.swing.table.TableColumn;

/**
 * A table to display a ResultSet
 * @author Stephen Phillips
 *
 */
public class ResultsTable extends JTable {
	// from: http://forums.sun.com/thread.jspa?forumID=54&messageID=2532529&threadID=527301
	private static final int DEFAULT_COLUMN_PADDING = 5;
	
	public ResultsTable() {
		super(new ResultsModel());
		this.setCellEditor(new ResultsCellEditor());
		this.setColumnModel(new ResultsColumnModel());
		this.setDefaultRenderer(ResultsCell.class, new ResultsCell());
		this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	}
	
	public ResultSet getResultSet() {
		ResultsModel model = (ResultsModel)this.getModel();
		return model.getResultSet();
	}

	public void setResultSet(ResultSet results) {
		ResultsModel model = (ResultsModel)this.getModel();
		model.setResultSet(results);
		ResultsColumnModel headings = (ResultsColumnModel) this.getColumnModel();
		headings.setResults(results);
		
		ResultsCell cell = (ResultsCell)getCellRenderer(0, 0).getTableCellRendererComponent(this, model.getValueAt(0, 0), false, false, 0, 0);
		int margin = cell.getMargin().left + cell.getMargin().right;
		int cellSpacing = this.getIntercellSpacing().width;
		FontMetrics fm = cell.getFontMetrics(cell.getFont());
		
		// set column widths
		if(results != null) {
			for(int x=0; x<headings.getColumnCount(); x++) {
				cell = (ResultsCell)getCellRenderer(0, 0).getTableCellRendererComponent(this, model.getValueAt(0, 0), false, false, 0, 0);
				margin = cell.getMargin().left + cell.getMargin().right;
				fm = cell.getFontMetrics(cell.getFont());
	
				TableColumn column = headings.getColumn(x);
				String columnLabel = column.getHeaderValue().toString();
				int headingWidth = fm.stringWidth(columnLabel);
				headingWidth += margin;
				headingWidth += cellSpacing;
				headingWidth += DEFAULT_COLUMN_PADDING;
				int width = model.getMaxCharacterLength(x);
				width += margin;
				width += cellSpacing;
				width += DEFAULT_COLUMN_PADDING;
				if(headingWidth > width) {
					width = headingWidth;
				}
				column.setPreferredWidth(width);
			}
		}
	}
}
